import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ConstructioninfoService } from '../constructioninfo.service';
import { StorageService } from '../../../../common/storage.service';
import { TimeConfigClass } from "../../../../common/common-config";
@Component({
  selector: 'app-list-constructioninfo',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css'],
  providers: [ConstructioninfoService]
})
export class ListConstructioninfoComponent implements OnInit {
  paramObj: any = {}; // 最终查询条件
  searchObj: any = {}; // 简易查询条件
  isShowH: boolean = false; // 高级查询是否显示
  totalRecords: number = 0; // 数据条数据
  listData: any[] = []; // 表格数据
  selectedDatas: any = []; // 选中的数据
  dataHead: any[] = []; // 表格表头
  statusDefault: any = { code: '', name: '全部' }; // 状态默认值
  searchHighObj: any = {}; // 高级搜索条件
  status: any[] = []; // 状态
  selectStatus: any = {}; // 选中的状态
  statusH: any[] = []; // 高级搜索状态数据
  selectedHStatus: any = {}; // 高级查询选中的状态
  organizationArray: any[] = []; // 组织数据
  seletcedOrganization: any; // 选中的组织数据
  seletcedHOrganization: any; // 选中的组织数据
  selectedTemplate: any = {}; // 选中的模板数据
  template: any[] = []; // 模板数据
  contractCompletedStartDateMax: Date; // 合同开始最大的时间
  contractCompletedEndDateMin: Date; // 合同结束最小的时间
  pageSize: number; // 分页大小
  pageNo: number; // 当前页
  isAgainOrder: boolean = false; // 重新派单弹出框
  operation: any[] = []; // 重新分给
  seletcedOperation: any = {};
  operationError: string = ''; //
  managerFlag: boolean = false; // 项目经理弹窗状态
  supervisorFlag: boolean = false; // 监理弹窗状态
  managerSearch: any = {}; // 经理查询条件
  supervisorSearch: any = {}; // 监理查询条件
  managerCols: any[] = []; // 经理弹窗表头数据
  managerData: any[] = []; // 经理弹窗表数据
  managerPageSize: number; // 经理弹窗分页大小
  managerPageNo: number; // 经理弹窗当前页
  managerTotalRecords: number; // 经理弹窗数据总数
  supervisorData: any[] = []; // 监理弹窗数据
  supervisorCols: any[] = []; // 监理弹窗表头数据
  supervisorPageSize: number; // 监理弹窗分页大小
  supervisorTotalRecords: number; // 监理弹窗数据总数
  supervisorPageNo: number; // 监理弹窗当前页
  supervisorOrgSelected: any; // 监理弹窗组织机构
  currentCity: any[]; // 监理弹出所在城市
  city: any = {}; // 监理弹出所在城市选中
  completedMaxTime: Date; // 高级查询时间最大值
  completedMinTime: Date; // 高级查询时间最小值
  isPunishShow: boolean = false; // 发起处罚弹出框
  punishmentsData: any = {}; // 传给处罚弹窗的数据
  lockoutMin: Date = undefined;

  timeConfig: any = new TimeConfigClass(); // 时间空间初始化
  isLockout: boolean = false;  //停工
  lockoutreason: any = [];  //停工原因
  selectedLockoutreason: any = {}; //选择的停工原因
  lockoutreasonError: any;  //停工原因错误提示
  lockoutEndTimeError: any;  //停工截止日期错误提示
  lockoutObj: any = {};  //停工数据对象

  eventObj: any = {};  //表格对象


  constructor(private router: Router, private constructioninfoService: ConstructioninfoService, private routeInfo: ActivatedRoute,
    private storage: StorageService) {
  }
  ngOnInit() {
    // 获取组织机构
    this.getOrganization();
    // 获取模板数据
    this.getTemplate();
    this.status = [...this.storage.getDic('constructionstatus')];
    this.statusH = [this.statusDefault, ...this.storage.getDic('constructionstatus')];
    this.selectStatus = this.statusDefault;
    this.lockoutreason = [{ name: '请选择', code: '' }, ...this.storage.getDic('lockoutreason')];
    this.selectedLockoutreason = { name: '请选择', code: '' };
    this.dataHead = [
      { field: 'sortNum', header: '序号', width: '80px', tem: true, hidden: false },
      { field: 'businessOpportunityCode', header: '项目编号', width: '200px', tem: true, hidden: false },
      { field: 'consumer', header: '客户', width: '150px', hidden: false },
      { field: 'decorationAddress', header: '装修地址', width: '150px', hidden: false },
      { field: 'organizationName', header: '所属组织', width: '150px', hidden: false },
      { field: 'contractEndDateText', header: '合同竣工日期', width: '150px', hidden: false },
      { field: 'contractConstructionDuration', header: '合同施工工期/天', width: '150px', hidden: true },
      { field: 'actualStartDateText', header: '实际开工日期', width: '150px', hidden: true },
      { field: 'houseAdviser', header: '设计师', width: '150px', hidden: true },
      { field: 'foreman', header: '项目经理', width: '150px', hidden: false },
      { field: 'supervisor', header: '监理', width: '150px', hidden: false },
      { field: 'templateName', header: '施工模板', width: '150px', tem: true, hidden: false },
      { field: 'progressRate', header: '工程进度', width: '150px', hidden: false },
      { field: 'contructionStatus', header: '状态', width: '200px', hidden: false, tem: true, dic: 'constructionstatus' },
    ];
    this.operation = [
      { code: 'user_jl', name: '监理' },
      { code: 'user_xmjl', name: '项目经理' },
    ];
    this.managerCols = [
      { field: 'fullName', header: '姓名', width: '140px' },
      { field: 'serviceArea', header: '服务区域', width: '110px' },
      { field: 'abilityText', header: '施工能力', width: '100px' },
      { field: 'workingCount', header: '在施工地', width: '80px' },
      { field: 'completeWorkCount', header: '总接单量', width: '80px' },
      { field: 'comlainCount', header: '被投诉', width: '70px' },
      { field: 'operation', header: '操作', width: '60px', tem: true }
    ];
    this.supervisorCols = [
      { field: 'fullName', header: '姓名', width: '140px' },
      { field: 'orgName', header: '所属组织', width: '100px' },
      { field: 'orgAddress', header: '办公地点', width: '110px' },
      { field: 'workingCount', header: '在施工地', width: '80px' },
      { field: 'completeWorkCount', header: '总接单量', width: '80px' },
      { field: 'comlainCount', header: '被投诉', width: '70px' },
      { field: 'operation', header: '操作', width: '60px', tem: true }
    ];


  }

  /**
   * 简易查询条件整合
   */
  normalSearchFun() {
    this.searchHighObj = {};
    this.selectedHStatus = {};
    this.seletcedHOrganization = undefined;
    this.selectedTemplate = {};
    this.completedMaxTime = undefined;
    this.completedMinTime = undefined;
    this.selectedDatas = [];
    // 状态
    if (this.selectStatus && this.selectStatus.code) {
      this.searchObj['contructionStatus'] = this.selectStatus.code;
    } else {
      delete this.searchObj['contructionStatus'];
    }
    // 组织机构
    if (this.seletcedOrganization && this.seletcedOrganization['code']) {
      this.searchObj['organizationCode'] = this.seletcedOrganization['code'];
    } else {
      delete this.searchObj['organizationCode'];
    }
    // 搜索文本框
    this.searchObj['searchValue'] = this.searchObj['searchValue'] ? this.searchObj['searchValue'].trim() : '';
    if (!this.searchObj['searchValue']) {
      delete this.searchObj['searchValue'];
    }
    // 合同竣工时间
    if (this.searchObj['contractEndStartDate']) {
      this.searchObj['contractEndStartDate'] = this.searchObj['contractEndStartDate'];
    } else {
      delete this.searchObj['contractEndStartDate'];
    }
    if (this.searchObj['contractEndEndDate']) {
      this.searchObj['contractEndEndDate'] = this.searchObj['contractEndEndDate'];
    } else {
      delete this.searchObj['contractEndEndDate'];
    }
    // 装修区域
    this.searchObj['decorationAddress'] = this.searchObj['decorationAddress'] ? this.searchObj['decorationAddress'].trim() : '';
    if (!this.searchObj['decorationAddress']) {
      delete this.searchObj['decorationAddress'];
    }
    this.paramObj = Object.assign({}, this.searchObj);
  }
  /**
  * 高级查询条件整合
  */
  advanceSearchFun() {
    this.selectStatus = this.statusDefault;
    this.seletcedOrganization = undefined;
    this.searchObj = {};
    this.contractCompletedStartDateMax = undefined;
    this.contractCompletedEndDateMin = undefined;
    // 状态
    if (this.selectedHStatus && this.selectedHStatus.code) {
      this.searchHighObj['contructionStatus'] = this.selectedHStatus.code;
    } else {
      delete this.searchHighObj['contructionStatus'];
    }
    // 组织机构
    if (this.seletcedHOrganization && this.seletcedHOrganization.code) {
      this.searchHighObj['organizationCode'] = this.seletcedHOrganization.code;
    } else {
      delete this.searchHighObj['organizationCode'];
    }
    // 施工模板
    if (this.selectedTemplate && this.selectedTemplate.id) {
      this.searchHighObj['templateId'] = this.selectedTemplate.id;
    } else {
      delete this.searchHighObj['templateId'];
    }
    // 客户姓名
    this.searchHighObj.consumerName = this.searchHighObj.consumerName ? this.searchHighObj.consumerName.trim() : '';
    if (!this.searchHighObj['consumerName']) {
      delete this.searchHighObj['consumerName'];
    }
    // 合同竣工开始
    if (!this.searchHighObj['contractEndStartDate']) {
      delete this.searchHighObj['contractEndStartDate'];
    }
    // 合同竣工结束
    if (!this.searchHighObj['contractEndEndtDate']) {
      delete this.searchHighObj['contractEndEndtDate'];
    }
    // 项目经理
    this.searchHighObj.foremanName = this.searchHighObj.foremanName ? this.searchHighObj.foremanName.trim() : '';
    if (!this.searchHighObj['foremanName']) {
      delete this.searchHighObj['foremanName'];
    }
    // 设计师
    this.searchHighObj.houseAdviserName = this.searchHighObj.houseAdviserName ? this.searchHighObj.houseAdviserName.trim() : '';
    if (!this.searchHighObj['houseAdviserName']) {
      delete this.searchHighObj['houseAdviserName'];
    }
    // 装修区域
    this.searchHighObj.decorationAddress = this.searchHighObj.decorationAddress ? this.searchHighObj.decorationAddress.trim() : '';
    if (!this.searchHighObj['decorationAddress']) {
      delete this.searchHighObj['decorationAddress'];
    }
    // 项目编号
    this.searchHighObj.businessOpportunityCode = this.searchHighObj.businessOpportunityCode ?
      this.searchHighObj.businessOpportunityCode.trim() : '';
    if (!this.searchHighObj['businessOpportunityCode']) {
      delete this.searchHighObj['businessOpportunityCode'];
    }
    // 客户手机号
    this.searchHighObj.consumerPhone = this.searchHighObj.consumerPhone ? this.searchHighObj.consumerPhone.trim() : '';
    if (!this.searchHighObj['consumerPhone']) {
      delete this.searchHighObj['consumerPhone'];
    }
    // 监理
    this.searchHighObj.supervisorName = this.searchHighObj.supervisorName ? this.searchHighObj.supervisorName.trim() : '';
    if (!this.searchHighObj['supervisorName']) {
      delete this.searchHighObj['supervisorName'];
    }
    this.paramObj = Object.assign({}, this.searchHighObj);
  }

  /**
   * 重置高级查询条件
   */
  resetHSearch() {
    this.searchHighObj = {};
    this.selectedHStatus = {};
    this.seletcedHOrganization = undefined;
    this.selectedTemplate = {};
  }


  /**
   * 查询按钮
   */
  search(param) {
    this.storage.loading();
    let post = Object.assign(param, this.paramObj);
    this.constructioninfoService.getConstructionmanageList(post).then((data) => {
      if (data.result) {
        this.listData = data.data.list;
        this.totalRecords = data.data.totalCount;
        this.storage.loadout();
      } else {
        this.storage.loadout();
        this.storage.messageService.emit({ severity: 'error', detail: data.msg });
      }
    });
  }

  /**
   * 重新派单
   */
  againOrder() {
    if (this.selectedDatas.length === 1) {
      if (this.selectedDatas[0].templateId) {
        if (this.selectedDatas[0].contructionStatus === 'constructionstatus_180108000001' || this.selectedDatas[0].contructionStatus === 'constructionstatus_180108000002') {
          this.isAgainOrder = true;
          this.seletcedOperation = {};
          this.operationError = '';
        } else {
          this.storage.makesureService.emit({
            message: '该工程' + this.selectedDatas[0].contructionStatusText + '，不允许重新派单，请重新选择！',
            header: '提示',
            rejectLabel: '取消',
            acceptLabel: '确定',
            acceptVisible: false,
            rejectVisible: false,
            accept: () => {
            },
            reject: () => {
              this.selectedDatas = [];
            }
          });
        }
      } else {
        this.storage.makesureService.emit({
          message: '未找到适用的施工模板，请先去“模板管理”中维护适用的施工模板，再重新匹配后即可正常派单',
          header: '提示',
          rejectLabel: '取消',
          acceptLabel: '确定',
          acceptVisible: false,
          rejectVisible: false,
          accept: () => {
          },
          reject: () => {
            this.selectedDatas = [];
          }
        });
      }

    } else if (this.selectedDatas.length === 0) {
      this.storage.makesureService.emit({
        message: '请选择要操作的数据！',
        header: '提示',
        rejectLabel: '取消',
        acceptLabel: '确定',
        acceptVisible: false,
        rejectVisible: false,
        accept: () => {
        },
        reject: () => {
        }
      });

    } else if (this.selectedDatas.length > 1) {
      this.storage.makesureService.emit({
        message: '只能勾选一条数据！',
        header: '提示',
        rejectLabel: '取消',
        acceptLabel: '确定',
        acceptVisible: false,
        rejectVisible: false,
        accept: () => {
        },
        reject: () => {
          this.selectedDatas = [];
        }
      });
    }
  }
  /**
   * 分页参数整理
   * @param event
   */
  onPage(event?) {
    let pageConfig: any = {};
    this.pageSize = event.rows;
    const pageTem = parseInt((event.first / event.rows).toString(), 0);
    this.pageNo = pageTem + 1;
    pageConfig['pageSize'] = this.pageSize;
    pageConfig['pageNo'] = this.pageNo;
    this.search(pageConfig);
  }


  /**
   * 修改日期控件结束时间
   * @param type
   */
  updateCalendarStartTime(type) {
    switch (type) {
      case 'contract':
        this.contractCompletedEndDateMin = new Date(this.searchObj.contractEndStartDate);
        break;
      case 'hContract':
        this.completedMinTime = new Date(this.searchHighObj.contractEndStartDate);
        break;
    }
  }

  /**
   *  修改日期控件开始时间
   * @param type
   */
  updateCalendarEndTime(type) {
    switch (type) {
      case 'contract':
        this.contractCompletedStartDateMax = new Date(this.searchObj.contractEndEndDate);
        break;
      case 'hContract':
        this.completedMaxTime = new Date(this.searchHighObj.contractEndEndtDate);
        break;
    }
  }

  /**
   * 时间控件清空，处理最大值
   * @param type
   */
  clearStart(type) {
    switch (type) {
      case 'contract':
        this.contractCompletedEndDateMin = undefined;
        break;
      case 'hContract':
        this.completedMinTime = undefined;
        break;
    }
  }
  /**
   * 时间控件清空，处理最小值
   * @param type
   */
  clearEnd(type) {
    switch (type) {
      case 'contract':
        this.contractCompletedStartDateMax = undefined;
        break;
      case 'hContract':
        this.completedMaxTime = undefined;
        break;
    }
  }


  /**
   * 重新分配验证
   */
  operationCK() {
    if (!this.seletcedOperation['name']) {
      this.operationError = '请选择重新分配';
    } else {
      this.operationError = '';
    }
  }

  /**
   * 选择重新 确定按钮
   */
  selectOperation() {
    if (!this.seletcedOperation['name']) {
      this.operationError = '请选择重新分配';
      return;
    } else {
      this.operationError = '';
      // 项目经理
      if (this.seletcedOperation.code === 'user_xmjl') {
        this.managerData = [];
        this.managerSearchFn();


      } else if (this.seletcedOperation.code === 'user_jl') { // 监理
        this.city = {
          areaCode: this.selectedDatas[0].decorationDistrictCode,
          cityCode: this.selectedDatas[0].decorationCityCode,
          merge: this.selectedDatas[0].decorationProvinceAndCityAndArea,
          provinceCode: this.selectedDatas[0].decorationProvinceCode
        };
        this.supervisorData = [];
        this.supervisorSearchFn();

      }
    }
  }

  /**
   * 匹配模板
   */
  matchingOrder() {
    if (this.selectedDatas.length === 1) {
      if (this.selectedDatas[0].id) {
        this.storage.loading();
        this.constructioninfoService.rematchTemplate({ id: this.selectedDatas[0].id }).then((data) => {
          if (data.result) {
            this.storage.messageService.emit({ severity: 'success', detail: data.msg });
            this.selectedDatas = [];
            let pageConfig: any = {};
            pageConfig['pageSize'] = this.pageSize;
            pageConfig['pageNo'] = this.pageNo;
            this.search(pageConfig);
          } else {
            this.storage.loadout();
            this.storage.makesureService.emit({
              message: data.msg,
              header: '提示',
              rejectLabel: '取消',
              acceptLabel: '确定',
              acceptVisible: false,
              rejectVisible: false,
              accept: () => {
              },
              reject: () => {
              }
            });
          }
        });
      }
    } else if (this.selectedDatas.length === 0) {
      this.storage.makesureService.emit({
        message: '请选择要操作的数据！',
        header: '提示',
        rejectLabel: '取消',
        acceptLabel: '确定',
        acceptVisible: false,
        rejectVisible: false,
        accept: () => {
        },
        reject: () => {
        }
      });

    } else if (this.selectedDatas.length > 1) {
      this.storage.makesureService.emit({
        message: '只能勾选一条数据！',
        header: '提示',
        rejectLabel: '取消',
        acceptLabel: '确定',
        acceptVisible: false,
        rejectVisible: false,
        accept: () => {
        },
        reject: () => {
          this.selectedDatas = [];
        }
      });
    }
  }



  /**
   * 经理查询方法
   */
  managerSearchFn(event?) {
    this.managerSearch['searchValue'] = this.managerSearch['searchValue'] ? this.managerSearch['searchValue'].trim() : '';
    if (!this.managerSearch['searchValue']) {
      delete this.managerSearch['searchValue'];
    }
    if (event && event.rows) {
      this.managerPageSize = event.rows;
      const pageTem = parseInt((event.first / event.rows).toString(), 0);
      this.managerPageNo = pageTem + 1;
      this.managerSearch['pageSize'] = this.managerPageSize;
      this.managerSearch['pageNo'] = this.managerPageNo;
    } else {
      this.managerSearch['pageSize'] = 20;
      this.managerSearch['pageNo'] = 1;
    }
    this.managerSearch['userType'] = 'user_xmjl';
    this.managerSearch['infoId'] = this.selectedDatas[0].id;
    this.storage.loading();
    this.constructioninfoService.getManager(this.managerSearch).then((data) => {
      if (data.result) {
        this.managerData = data.data.list;
        this.managerTotalRecords = data.data.totalCount;
        this.managerFlag = true;
        this.storage.loadout();
      } else {
        this.storage.loadout();
        this.storage.messageService.emit({ severity: 'error', detail: data.msg });
      }
    });
  }

  /**
   * 监理查询方法
   */
  supervisorSearchFn(event?) {
    // 查询条件
    this.supervisorSearch['searchValue'] = this.supervisorSearch['searchValue'] ? this.supervisorSearch['searchValue'].trim() : '';
    if (!this.supervisorSearch['searchValue']) {
      delete this.supervisorSearch['searchValue'];
    }
    // 组织架构
    if (this.supervisorOrgSelected && this.supervisorOrgSelected.code) {
      this.supervisorSearch['orgCode'] = this.supervisorOrgSelected.code;
    } else {
      delete this.supervisorSearch['orgCode'];
    }
    // 住址区域
    if (this.city && this.city.cityCode) {
      this.supervisorSearch['cityCode'] = this.city.cityCode;
    } else {
      delete this.supervisorSearch['cityCode'];
    }
    if (this.city && this.city.areaCode) {
      this.supervisorSearch['areaCode'] = this.city.areaCode;
    } else {
      delete this.supervisorSearch['areaCode'];
    }
    if (this.city && this.city.provinceCode) {
      this.supervisorSearch['provinceCode'] = this.city.provinceCode;
    } else {
      delete this.supervisorSearch['provinceCode'];
    }

    if (event && event.rows) {
      this.managerPageSize = event.rows;
      const pageTem = parseInt((event.first / event.rows).toString(), 0);
      this.managerPageNo = pageTem + 1;
      this.supervisorSearch['pageSize'] = this.managerPageSize;
      this.supervisorSearch['pageNo'] = this.managerPageNo;
    } else {
      this.supervisorSearch['pageSize'] = 20;
      this.supervisorSearch['pageNo'] = 1;
    }
    this.supervisorSearch['userType'] = 'user_jl';
    this.supervisorSearch['infoId'] = this.selectedDatas[0].id;
    this.storage.loading();
    this.constructioninfoService.getManager(this.supervisorSearch).then((data) => {
      if (data.result) {
        this.supervisorData = data.data.list;
        this.supervisorTotalRecords = data.data.totalCount;
        this.storage.loadout();
        this.supervisorFlag = true;
      } else {
        this.storage.loadout();
        this.storage.messageService.emit({ severity: 'error', detail: data.msg });
      }
    });
  }

  /**
   * 监理城市所在城市选择
   */
  cityBlur() {
    setTimeout(() => {
      if (typeof this.city === 'string') {
        this.city = undefined;
        this.supervisorSearchFn();
      }
    }, 300);
  }
  /**
   * 选中新项目经理
   */
  selectedManager(selected) {
    if (selected.id) {
      this.storage.makesureService.emit({
        message: '是否确认派单',
        header: '提示',
        rejectLabel: '取消',
        acceptLabel: '确定',
        acceptVisible: true,
        rejectVisible: true,
        accept: () => {
          this.storage.loading();
          let post = { id: this.selectedDatas[0].id, dispatchId: selected.id, dispatchCode: selected.code, type: 'foreman' };
          this.constructioninfoService.redispatch(post).then((data) => {
            if (data.result) {
              this.storage.loadout();
              this.storage.messageService.emit({ severity: 'success', detail: data.msg });
              this.selectedDatas = [];
              this.isAgainOrder = false;
              this.managerFlag = false;
              this.managerSearch = {};
              let pageConfig: any = {};
              pageConfig['pageSize'] = this.pageSize;
              pageConfig['pageNo'] = this.pageNo;
              this.search(pageConfig);
            } else {
              this.storage.loadout();
              this.storage.messageService.emit({ severity: 'error', detail: data.msg });
            }
          });
        },
        reject: () => {
        }
      });

    }
  }

  /**
   * 选中监理
   * @param selected
   */
  selectedSupervisor(selected) {
    if (selected.id) {
      this.storage.makesureService.emit({
        message: '是否确认派单',
        header: '提示',
        rejectLabel: '取消',
        acceptLabel: '确定',
        acceptVisible: true,
        rejectVisible: true,
        accept: () => {
          this.storage.loading();
          let post = { id: this.selectedDatas[0].id, dispatchId: selected.id, dispatchCode: selected.code, type: 'supervisor' };
          this.constructioninfoService.redispatch(post).then((data) => {
            if (data.result) {
              this.storage.loadout();
              this.storage.messageService.emit({ severity: 'success', detail: data.msg });
              this.selectedDatas = [];
              this.isAgainOrder = false;
              this.supervisorFlag = false;
              this.supervisorSearch = {};
              this.supervisorOrgSelected = undefined;
              let pageConfig: any = {};
              pageConfig['pageSize'] = this.pageSize;
              pageConfig['pageNo'] = this.pageNo;
              this.search(pageConfig);
            } else {
              this.storage.loadout();
              this.storage.messageService.emit({ severity: 'error', detail: data.msg });
            }
          });
        },
        reject: () => {
        }
      });

    }
  }
  /**
   * 清空查询条件
   */
  resetSupervisor() {
    this.supervisorOrgSelected = undefined;
    this.supervisorSearch = {};
    this.city = undefined;
  }

  /**
   * 处罚按钮
   */
  punishments() {
    if (this.selectedDatas.length === 1) {
      this.constructioninfoService.getInfoStatus(this.selectedDatas[0].id).then(
        data => {
          if (data.result) {
            if (data.data == 'constructionstatus_180108000006') {
              this.storage.messageService.emit({ severity: 'error', detail: '该项目已中止，无法进行此操作！' });
              return false
            } if (data.data == 'constructionstatus_180108000004') {
              this.storage.messageService.emit({ severity: 'error', detail: '该项目已竣工，无法进行此操作！' });
              return false
            } else {
              // if (this.selectedDatas[0].templateId) {
              if (this.selectedDatas[0].id) {
                this.punishmentsData.infoId = this.selectedDatas[0].id;
                this.punishmentsData.triggerType = '';
                this.punishmentsData.triggerId = '';
                this.isPunishShow = true;
              }
              // } else {
              //   this.storage.makesureService.emit({
              //     message: '未找到适用的施工模板，请先去“模板管理”中维护适用的施工模板，再重新匹配后即可正常派单',
              //     header: '提示',
              //     rejectLabel: '取消',
              //     acceptLabel: '确定',
              //     acceptVisible: false,
              //     rejectVisible: false,
              //     accept: () => {
              //     },
              //     reject: () => {
              //     }
              //   });
              // }
            }
          }
        }
      );
    } else if (this.selectedDatas.length === 0) {
      this.hint('请选择要操作的数据！')
    } else if (this.selectedDatas.length > 1) {
      this.hint('只能勾选一条数据！')
    }


  }

  /**
   * 所在区域自动补齐
   */
  selectCurrentCity(event) {
    let post: any = { q: event.query };
    this.constructioninfoService.autoCurrentCity(post).then((data) => {
      if (data.result) {
        this.currentCity = data.data;
      } else {
        this.storage.loadout();
        this.storage.messageService.emit({ severity: 'error', detail: data.msg });
      }
    });
  }

  /**
  * 获取公司数据
  */
  getOrganization() {
    this.constructioninfoService.getTree().then(
      data => {
        if (data.result) {
          this.organizationArray = [{
            label: '全部',
            leaf: false,
            orgType: '',
            parentCode: '0',
            info: { companyName: '全部', companyCode: -1 },
            code: '',
            children: data.data
          }];
          this.expandAll(this.organizationArray);
        }
      }
    );
  }

  /**
   * 获取模板数据
   */
  getTemplate() {
    this.constructioninfoService.getTemplate().then(
      data => {
        if (data.result) {
          this.template = [{ id: 0, name: '全部' }, ...data.data];
        } else {
          this.storage.messageService.emit({ severity: 'error', detail: '模板数据加载失败！' });
        }
      }
    );
  }

  /**
   * 修改发起处罚
   */
  changePunishShow(event) {
    this.isPunishShow = event;
    this.selectedDatas = [];
  }

  /**
   * 下拉树数据全部展开
   * @param data
   */
  expandAll(data) {
    data.forEach(node => {
      this.expandRecursive(node, true);
    });
  }
  /**
  * 设置树的展开收缩
  * @param data
  */
  private expandRecursive(node, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

  /**
   * Description: 停工
   */
  lockout(event?) {
    this.lockoutObj = {};
    this.lockoutEndTimeError = '';
    this.lockoutreasonError = '';
    this.selectedLockoutreason = { name: '请选择', code: '' };
    if (this.selectedDatas.length === 0) {
      this.hint('请选择要操作的数据！');
    } else if (this.selectedDatas.length > 1) {
      this.hint('只能勾选一条数据！');
    } else {
      let data = this.selectedDatas[0];
      if (data.contructionStatus != 'constructionstatus_180108000002' && data.contructionStatus != 'constructionstatus_180108000003') {
        this.storage.messageService.emit({ severity: 'error', detail: '该项目目前状态无法进行此操作！' });
      } else {
        this.constructioninfoService.getCurrentDate().then((time) => {
          if (time.result) {
            this.lockoutMin = new Date(time.data.date);
          } else {
            this.storage.messageService.emit({ severity: 'error', detail: '服务器时间获取失败' })
          }
        });
        this.isLockout = true;
        this.eventObj = event;
      }
    }
  }

  /**
   * Description: 复工
   */
  recover(event?) {
    if (this.selectedDatas.length === 0) {
      this.hint('请选择要操作的数据！');
    } else if (this.selectedDatas.length > 1) {
      this.hint('只能勾选一条数据！');
    } else {
      let data = this.selectedDatas[0];
      if (data.contructionStatus != 'constructionstatus_180108000005') {
        if (data.contructionStatus == 'constructionstatus_180108000006') {
          this.storage.messageService.emit({ severity: 'error', detail: '由于客户要求中止合同项目停工，请等待家具顾问处理！' });
        } else {
          this.storage.messageService.emit({ severity: 'error', detail: '只有已停工的项目才能进行此操作！' });
        }
      } else {
        if (data['stopSource'] == 'stopconstructionresource_180208000016') {
          this.storage.messageService.emit({ severity: 'error', detail: '由于客户要求中止合同项目停工，请等待家具顾问处理！' });
        } else {
          this.storage.makesureService.emit({
            message: '是否确认复工？',
            header: '确认复工',
            rejectLabel: '取消',
            acceptLabel: '确定',
            acceptVisible: true,
            rejectVisible: true,
            accept: () => {
              this.constructioninfoService.getInfoStatus(this.selectedDatas[0].id).then(
                data => {
                  if (data.result) {
                    if (data.data != 'constructionstatus_180108000005') {
                      if (data.data == 'constructionstatus_180108000006') {
                        this.storage.messageService.emit({ severity: 'error', detail: '由于客户要求中止合同项目停工，请等待家具顾问处理！' });
                      } else {
                        this.storage.messageService.emit({ severity: 'error', detail: '该项目目前状态无法进行此操作！' });
                      }
                    } else {
                      this.storage.loading();
                      this.constructioninfoService.recover(this.selectedDatas[0].id).then(
                        data => {
                          this.storage.loadout();
                          if (data.result) {
                            this.onPage(event);
                            this.storage.messageService.emit({ severity: 'success', detail: '操作成功！' });
                            this.selectedDatas = [];
                          } else {
                            this.storage.messageService.emit({ severity: 'error', detail: data.msg });
                          }
                        }
                      );
                    }
                  }
                });
            },
            reject: () => {
            }
          });
        }
      }
    }
  }

  /**
   * Description: 提示
   * @Note:
   */
  hint(msg) {
    this.storage.makesureService.emit({
      message: msg,
      header: '提示',
      rejectLabel: '取消',
      acceptLabel: '确定',
      acceptVisible: false,
      rejectVisible: false,
      accept: () => {
      },
      reject: () => {
      }
    });
  }


  /**
   * Description: 停工
   */
  lockoutFun() {
    let flag: boolean = true;
    if (!this.lockoutObj['lockoutEndTime']) {
      this.lockoutEndTimeError = '请选择停工截止日期';
      flag = false;
    }
    if (this.selectedLockoutreason) {
      if (this.selectedLockoutreason.code == this.lockoutreason[0].code) {
        this.lockoutreasonError = '请选择停工原因';
        flag = false;
      }
    } else {
      this.lockoutreasonError = '请选择停工原因';
      flag = false;
    }
    if (!flag) {
      return false
    }
    this.storage.loading();
    this.lockoutObj.id = this.selectedDatas[0].id;
    this.lockoutObj.lockoutreason = this.selectedLockoutreason.code;
    this.constructioninfoService.getInfoStatus(this.selectedDatas[0].id).then(
      data => {
        if (data.result) {
          if (data.data != 'constructionstatus_180108000002' && data.data != 'constructionstatus_180108000003') {
            this.storage.messageService.emit({ severity: 'error', detail: '该项目目前状态无法进行此操作！' });
            this.storage.loadout();
          } else {
            this.constructioninfoService.lockout(this.lockoutObj).then(
              data => {
                this.storage.loadout();
                if (data.result) {
                  this.isLockout = false;
                  this.onPage(this.eventObj);
                  this.storage.messageService.emit({ severity: 'success', detail: '操作成功！' });
                  this.eventObj = {};
                  this.selectedDatas = [];
                } else {
                  this.storage.messageService.emit({ severity: 'error', detail: data.msg });
                }
              }
            );
          }
        }
      });
  }


  /**
   * Description: 停工截止日期验证
   */
  getDelayEndTimeCk() {
    if (!this.lockoutObj['lockoutEndTime']) {
      this.lockoutEndTimeError = '请选择停工截止日期';
    } else {
      this.lockoutEndTimeError = '';
    }
  }


  /**
   * Description: 验证停工原因
   */
  checkFiled() {
    if (this.selectedLockoutreason) {
      if (this.selectedLockoutreason.code == this.lockoutreason[0].code) {
        this.lockoutreasonError = '请选择停工原因！'
      } else {
        this.lockoutreasonError = ''
      }
    }
  }

}
